package com.un.ebs.product.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.*;
import com.un.ebs.product.ProductConfigureCode;
import com.un.ebs.product.domain.*;
import com.un.ebs.product.dto.ProductSkuByUpdateDto;
import com.un.ebs.product.dto.ProductSkuVo;
import com.un.ebs.product.dto.SkuItemUpdateDto;
import com.un.ebs.product.enums.ProductBomTypeEnum;
import com.un.ebs.product.service.ProductSkuService;
import com.un.ebs.sys.dto.ObjectParentAndIndexChangeDto;
import com.un.ebs.sys.service.ConfigureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liubo
 * @since 2019-09-16
 */
@RestController
@RequestMapping("/productSku")
@Api(value = "product-sku", description = "商品sku")
public class ProductSkuController {

    @Resource
    private ProductSkuService service;

    @Resource
    private ConfigureService configureService;

    @PostMapping("updatePrice")
    @ApiOperation("修改 sku 销售价格")
    public WebResult updatePrice(@RequestParam String id, @RequestParam(required = false) String code, @RequestParam Double price, @RequestParam(required = false) Boolean isVirtual, @RequestParam(required = false) Boolean isPriceConfer) {
        service.update(id, code, price, isVirtual, isPriceConfer);
        return WebUtils.success();
    }

    @PostMapping("update")
    @ApiOperation("修改 sku ")
    public WebResult update(@RequestParam String id, @RequestParam(required = false) String code, @RequestParam Double price, @RequestParam(required = false) Boolean isVirtual, @RequestParam(required = false) Boolean isPriceConfer) {
        service.update(id, code, price, isVirtual, isPriceConfer);
        return WebUtils.success();
    }

    @PostMapping("updateSku")
    @ApiOperation("修改 sku ")
    public WebResult updateSku(@RequestBody @Validated ProductSkuByUpdateDto req) {
        service.updateSku(req);
        return WebUtils.success();
    }

    @PostMapping("addItem")
    @ApiOperation("往SKU中添加包含的子SKU")
    public WebResult addInclude(@RequestParam String skuId, @RequestParam String includeSkuId, @RequestParam Double qty) {
        service.addInclude(skuId, includeSkuId, qty, null);
        return WebUtils.success();
    }

    @PostMapping("addItemByCode")
    @ApiOperation("往SKU中添加包含的子SKU")
    public WebResult addIncludeByCode(@RequestParam String skuId, @RequestParam String skuCode, @RequestParam Double qty, @RequestParam ProductBomTypeEnum bomType) {
        service.addIncludeByCode(skuId, skuCode, qty, bomType);
        return WebUtils.success();
    }

    @DeleteMapping("removeItem")
    @ApiOperation("删除SKU中的子SKU")
    public WebResult removeInclude(@RequestParam String skuId, @RequestParam String includeSkuId) {
        service.removeInclude(skuId, includeSkuId);
        return WebUtils.success();
    }

    @PostMapping("removeItem/{id}")
    @DeleteMapping("removeItem/{id}")
    @ApiOperation("删除SKU中的子SKU")
    public WebResult removeInclude(@PathVariable("id") String id) {
        service.removeInclude(id);
        return WebUtils.success();
    }

    @PostMapping("updateItemQty/{id}/{qty}")
    @ApiOperation("修改Sku 套餐中中SKU的数量")
    public WebResult updateIncludeQty(@PathVariable("id") String id, @PathVariable("qty") Double qty) {
        service.updateIncludeQty(id, qty);
        return WebUtils.success();
    }

    @PostMapping("updateSkuItem")
    @ApiOperation("修改Sku 套餐中中SKU的数量")
    public WebResult updateSkuItem(@RequestBody @Validated SkuItemUpdateDto req) {
        service.updateSkuItem(req);
        return WebUtils.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据主键获取单个 ProductSku")
    public WebResult<ProductSkuVo> getById(@PathVariable("id") String id) {
        return WebUtils.success(service.queryViewById(id));
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("无身份证的SKU查询")
    public WebResult<ProductSkuExt> buyById(@PathVariable String id) {
        ProductSkuExt sku = service.queryViewById(id);
        if (sku == null) {
            throw new BusinessEntityNotFoundException(id, "SKU");
        }
        if (sku.getSpuIsDelete()) {
            throw new BusinessException("SPU已删除。");
        }
        if (sku.getIsDelete()) {
            throw new BusinessException("SKU已删除。");
        }
        if (sku.getSaleStart() != null) {
            Date curr = DateUtils.parseDate(new Date(), "yyyyMMdd");
            Date start = DateUtils.parseDate(sku.getSaleStart(), "yyyyMMdd");

            sku.getSaleStart().before(curr);
        }
        return WebUtils.success(sku);
    }

    @PostMapping("changeNode")
    @ApiOperation("修改套餐内SKU的交付关系。")
    public WebResult changeNode(@RequestBody List<ObjectParentAndIndexChangeDto> nodes) {
        service.changeNode(nodes);
        return WebUtils.success();
    }

    @PostMapping("updateLackStatus")
    @ApiOperation("修改允许投料开工状态，按SKU。")
    public WebResult updateLackStatus(@RequestParam String id, @RequestParam Boolean allowStatus) {
        service.updateLackStatus(id, allowStatus);
        return WebUtils.success();
    }

    @PostMapping("updateLackStatusByItemId")
    @ApiOperation("修改允许投料开工状态，按SKU 中的 item。")
    public WebResult updateLackStatusByItemId(@RequestParam String skuItemId, @RequestParam Boolean allowStatus) {
        List<String> ids = new ArrayList<>();
        ids.add(skuItemId);
        service.updateLackStatusByItemId(ids, allowStatus);
        return WebUtils.success();
    }

    @GetMapping("listPage")
    @ApiOperation("查询SKU")
    public WebResult<IPage<ProductSkuExt>> listPage(@RequestParam(required = false) String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.query(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), pageSize, pageIndex));
    }

    @GetMapping("listSaleByTomb")
    @ApiOperation("查询已售墓位商品")
    public WebResult<IPage<ProductSaleQueryByTomb>> listSaleByTomb(@RequestParam(required = false) String searchText, @RequestParam(required = false) String classId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.querySaleByTomb(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), classId, pageSize, pageIndex));
    }

    @GetMapping("listSku")
    @ApiOperation("查询")
    public WebResult<IPage<SkuExt>> listSku(@RequestParam(required = false) String searchText, @RequestParam(required = false) String classId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.querySku(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), classId, pageSize, pageIndex));
    }

    @GetMapping("listPageByMain")
    @ApiOperation("查询SKU，根据配置中所指定的主商品类型判定")
    public WebResult<IPage<ProductSkuExt>> listPageByMain(@RequestParam(required = false) String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryByMain(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), pageSize, pageIndex));
    }

    @GetMapping("listSubsidiary")
    @ApiOperation("查询SKU，辅材")
    public WebResult<IPage<SkuExt>> listSubsidiary(@RequestParam(required = false) String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
        String classId = configureService.getValueByCode(ProductConfigureCode.other_spu_class_id);
        if (StringUtils.isNullOrEmpty(classId)) {
            throw new BusinessException("没有指定辅材类别。");
        }
        return WebUtils.success(service.querySku(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), classId, pageSize, pageIndex));
    }

    @GetMapping("list/items/{skuId}")
    @ApiOperation("查询指定 SKU 的套餐明细")
    public WebResult<List<ProductSkuItemExt>> listItems(@PathVariable String skuId) {
        return WebUtils.success(service.queryItemBySkuId(skuId));
    }

    @GetMapping("listPageSkuItem")
    @ApiOperation("查询指定 SKU 的套餐明细")
    public WebResult<IPage<ProductSkuItemExt>> listPageItems(@RequestParam String skuId, @RequestParam(required = false) ProductBomTypeEnum bomType, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryItemBySkuId(skuId, bomType, pageSize, pageIndex));
    }

    @GetMapping("listCanSale")
    @ApiOperation(value = "listCanSale", notes = "")
    public WebResult<IPage<ProductSkuExt>> listCanSale(@RequestParam(value = "classId", required = false) String classId, @RequestParam(value = "productId", required = false) String productId, @RequestParam(value = "searchText", required = false) String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.query(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), null, null, true, null, pageSize, pageIndex));
    }

    @PostMapping("getSkuBySaleAttr")
    @ApiOperation(value = "getSkuBySaleAttr", notes = "")
    public WebResult<ProductSkuVo> getSkuBySaleAttr(@RequestParam(value = "productId") String productId, @RequestParam(required = false) String saleAttr) {
        return WebUtils.success(service.queryBySaleAttr(productId, saleAttr));
    }

    @PostMapping("/detail/getSkuBySaleAttr")
    @ApiOperation(value = "获取SKU ID")
    public WebResult<ProductSkuVo> getSkuIdBySaleAttr(@RequestParam(value = "productId") String productId, @RequestParam String saleAttr) {
        return WebUtils.success(service.queryBySaleAttr(productId, saleAttr));
    }

    @GetMapping("listPageByProductId")
    @ApiOperation(value = "listPageByProductId", notes = "")
    public WebResult<IPage<ProductSkuExt>> listPageByClass(@RequestParam String productId, @RequestParam Integer pageSize, @RequestParam Integer pageIndex) {
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        return WebUtils.success(service.query(null, null, productId, null, null, pageSize, pageIndex));
    }

    @GetMapping("listBom")
    @ApiOperation(value = "listBom", notes = "")
    public WebResult<IPage<ProductBomExt>> listBom(@RequestParam String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryBom(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), pageSize, pageIndex));
    }

    @GetMapping("listBomCost")
    @ApiOperation(value = "查询，产品标准成本")
    public WebResult<IPage<ProductBomCostExt>> listBomCost(@RequestParam String skuCode, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryBomCost(skuCode, pageSize, pageIndex));
    }

    @GetMapping("listBomCostItem")
    @ApiOperation(value = "查询，产品标准成本明细")
    public WebResult<IPage<ProductBomCostItemExt>> listBomCostItem(@RequestParam String skuId, @RequestParam(required = false) String bomSkuCode, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryBomItemCost(skuId, bomSkuCode, pageSize, pageIndex));
    }

    @GetMapping("listPageByClass")
    @ApiOperation(value = "listPageByClass", notes = "")
    public WebResult<IPage<ProductSkuExt>> listPageByClass(@RequestParam String classId, @RequestParam String searchText, @RequestParam int
            pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.query(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), classId, null, null, null, pageSize, pageIndex));
    }

    @GetMapping("listPurchaseCount")
    @ApiOperation(value = "查询外采SKU的供应商统计")
    public WebResult<IPage<ProductSkuPurchaseCountExt>> queryPurchaseCount(@RequestParam(required = false) String searchText, @RequestParam(required = false) @ApiParam("是否只查询无供应商的商品") Boolean notSupply, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryPurchaseCount(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), notSupply, pageSize, pageIndex));

    }

    @GetMapping("qrcode/{qrcode}")
    @ApiOperation(value = "根据二维码查询SKu")
    public WebResult<ProductSkuVo> listByQrcode(@PathVariable String qrcode) {
        return WebUtils.success(service.queryByQrcode(qrcode));
    }

    @PostMapping("qrcode/{qrcode}/{id}")
    @ApiOperation("绑定二维码到SKU")
    public WebResult bindQrcode(@PathVariable String id, @PathVariable String qrcode) {
        service.bindQrcode(id, qrcode);
        return WebUtils.success();
    }

    @PostMapping("delete/{id}")
    @ApiOperation("根据主键删除单个 ProductSku")
    public WebResult delete(@PathVariable("id") String id) {
        service.delete(id);
        return WebUtils.success();
    }

    @PostMapping("upperShelf/{skuId}")
    @ApiOperation("sku上线销售")
    public WebResult upperShelf(@PathVariable("skuId") String skuId) {
        service.upperShelf(skuId);
        return WebUtils.success();
    }

    @PostMapping("lowerShelf/{skuId}")
    @ApiOperation("sku下架")
    public WebResult lowerShelf(@PathVariable("skuId") String skuId) {
        service.lowerShelf(skuId);
        return WebUtils.success();
    }

    @GetMapping("print")
    @ApiOperation("打印")
    public void print(@RequestParam String id, HttpServletResponse response) {
        ProductSkuExt sku = service.queryViewById(id);
        if (sku == null) {
            throw new BusinessEntityNotFoundException(id, "SKU");
        }
        ReportUtils.print(sku, service.queryItemBySkuId(id), "/reports/prod_bom_detail.jrxml", response);
    }
}